/**
 * 入口中转
 * @author HuiSir q273250950
 * @git https://gitee.com/huisir001/
 * @blog http://www.zuifengyun.com/
 */

const fs = require('fs')
const path = require('path')
const Koa = require('koa')
const app = new Koa()
const render = require('koa-art-template')  //模板引擎
const static = require('koa-static')
const isDev = process.argv.includes('--dev')  //是否为开发模式
const {renderImports} = require('./config')

//路由模块(读取routes文件夹内所有文件)
let fsRoutes = fs.readdirSync('./routes') , routerModules = {}
fsRoutes.forEach(route=>{
    let basename = path.basename(route, '.js')
    routerModules[basename] = require(`./routes/${route}`)
})

//render 配置
render(app, {
    root: path.join(__dirname, 'views'),    //模板路径
    extname: '.html',   //后缀
    debug: isDev,   //true-开发环境,false-生产环境,生产环境默认：开启缓存、开启压缩
    imports:renderImports   //导入模版的全局变量,通过$imports访问
});

//静态资源
const staticPath = isDev?'/dev_static':'/static'
app.use(static(__dirname+staticPath))

//前台错误捕获(中间件)
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        ctx.response.status = err.statusCode || err.status || 500;
        ctx.response.type = 'html';
        ctx.response.body = err.error;
        ctx.app.emit('error', err, ctx); //如果错误被try...catch捕获，就不会触发error事件，故需要使用emit方法
    }
})

//启动路由routes
for (const key in routerModules) {
    if(routerModules[key] && Object.keys(routerModules[key]).length != 0) //判断是否为空对象
        app.use(routerModules[key].routes(), routerModules[key].allowedMethods())
}

//后台错误捕获
app.on('error', function(err) {
    console.error(new Date().toLocaleString(),err)
})

module.exports = app